#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#include "api/api.h"

int main(int argc, char *argv[])
{
	#if DEBUG >= 1
	printf("########## SENDER BEGINS ##########\n");
	#endif
	
	if( argc < 3 ) {
		printf("ERROR: WRONG ARGUMENT NUMBER\nusage: sender <serial_port> <file_path>\n");
		exit(-EXIT_FAILURE);
	}
	else if( argc >= 4 ) {
		baudrate = atoi(argv[3]);
		if( argc >= 5 ) {
			max_timeouts = (atoi(argv[4]) <= 2 ? 3 : atoi(argv[4]) ) ;
			if( argc >= 6 ) {
				if( atoi(argv[5]) > 0 )
					time_out = atoi(argv[5]);
			}
		}
	}
	
	int port_path;
	const char *portS0 = TTYS0_VALUE;
	const char *portS1 = TTYS1_VALUE;
	
	if( !strcmp(portS0, argv[1]) )
		port_path = TTYS0;
	else if ( !strcmp(portS1, argv[1]) )
		port_path = TTYS1;
	else {
		printf("ERROR: WRONG SERIAL PORT PATH.\nPlease try \"%s\" or \"%s\"\n", portS0, portS1);
		exit(-EXIT_FAILURE);
	}
		
	int port_fd;
	
	if( (port_fd = llopen(port_path, SENDER)) < 0 ) {
		printf("ERROR: LLOPEN FAILED.\n Return value: %d\n", port_fd);
		exit(-EXIT_FAILURE);
	}
	
	#if DEBUG >= 1
	printf("\n>>>>> Connection setup done <<<<<\n\n");
	#endif
	
	int file_fd;
	
	if ( (file_fd = open(argv[2], O_RDONLY)) < 0) {
		perror("ERROR Opening file\n");
		exit(-EXIT_FAILURE);
	}
		
	char buf[DATA_SIZE];
	int total_bytes = 0;
	int bytes_read = -1;
	int frame_counter = 0;

	llwrite(port_fd, argv[2], -CPACKET_START);
	
	while(bytes_read != 0)
	{
		bzero(&buf, DATA_SIZE);
		bytes_read = read(file_fd, &buf, DATA_SIZE);
		if(bytes_read == 0)
			break; //end of reading file
		if(bytes_read < 0)
		{
			perror("ERROR READING FROM FILE\n");
			exit(EXIT_FAILURE);
		}
		frame_counter++;
		total_bytes += bytes_read;
		llwrite(port_fd,buf,bytes_read);
		
		printf("frame counter = %d; byte counter = %d\n", frame_counter, total_bytes);
		fflush(stdout);
	}
	
	llwrite(port_fd, argv[2], -CPACKET_END);
	
	llclose(port_fd);
	printf("\n\nTOTAL BYTES TRANSFERRED: %d\n\n", total_bytes);
	
	return 0;
}

